#include <STC15F2K60S2.H>
#include "key.h"

unsigned char anjian()//获取按键按下状态
{ 
	unsigned char key=0;//没按下时为0
	if(P30==0){key=1;}//1 4 7 SW1短按、长按、双击时的值
	if(P31==0){key=2;}//2 5 8
	if(P32==0){key=3;}//3 6 9
	return key;
}

unsigned char keylook()//非阻塞获取键码
{
	static unsigned char befor,now,count=0,double_count=0;//上次、当前值，按下计时，两次按下间隔计时
	static unsigned char keynum=0,keynum_befor=0;//当前按下的键，上次按下的键
	befor=now;
	now=anjian();
	if(befor==now&&befor!=0)//持续低电平20ms视为按下，软件滤波
    {
        count++;//记录按下按键的时间
    }
	if(befor==1&&now==0)//松开按键
	{
		if(count>LONG_KEY_TIME)//长按
		{
			count=0;
			keynum=4;
		}
        else if (double_count)//双击
        {
            count=0;
            keynum=7;
            double_count=0;
        }
		else//短按
        {
            count=0;
            keynum=1;
            double_count=KEY_INTERVAL;//进入双击判断
        }
	}
	if(befor==2&&now==0)
	{
		if(count>LONG_KEY_TIME)
		{
			count=0;
			keynum=5;
		}
		else if (double_count)//双击
        {
            count=0;
            keynum=8;
            double_count=0;
        }
		else//短按
        {
            count=0;
            keynum=2;
            double_count=KEY_INTERVAL;//进入双击判断
        }
		
	}
	
	if(befor==3&&now==0)
	{
		if(count>LONG_KEY_TIME)
		{
			count=0;
			keynum=6;
		}
        else if (double_count)//双击
        {
            count=0;
            keynum=9;
            double_count=0;
        }
		else//短按
        {
            count=0;
            keynum=3;
            double_count=KEY_INTERVAL;//进入双击判断
        }
		
	}
    if(double_count)//在双击判断时，每进入一次keylook自减1，在减为0前按下第二次，响应为双击
    {
        double_count--;
        return 0;
    }
    else if(keynum)//键码非0
    {
        keynum_befor=keynum;
        keynum=0;
        return keynum_befor;
    }	    
    else
        return 0;
}
